package com.example.mybatispermission.controller;

import com.example.mybatispermission.entry.Permission;
import com.example.mybatispermission.entry.User;
import com.example.mybatispermission.mapper.PermissionMapper;
import lombok.AllArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Arrays;

@Controller
@RequestMapping("permission")
@AllArgsConstructor
public class PermissionController {
    private PermissionMapper permissionMapper;
    @GetMapping("user/insert")
    @RequiresPermissions("user:insert")
    public String getUserInsert(Model model){
        model.addAttribute("msg", "用户的插入");
        return "message";
    }
    @GetMapping("user/select")
    @RequiresPermissions("user:select")
    public String getUserSelect(Model model){
        model.addAttribute("msg", "用户的查看");
        return "message";
    }
    @GetMapping("user/delete")
    @RequiresPermissions("user:delete")
    public String getUserDelete(Model model){
        model.addAttribute("msg", "用户的删除");
        return "message";
    }
    @GetMapping("user/write")
    @RequiresPermissions(value = {"user:insert","user:delete","user:update"}, logical = Logical.OR)
    public String getUserWrite(Model model) {
        Subject subject = SecurityUtils.getSubject();
        String[] p = new String[]{"user:insert","user:delete","user:update"};
        Arrays.sort(p);
        User user = (User) subject.getPrincipal();
        String s = permissionMapper.getPermissionsByUser(user).stream().map(Permission::getName).filter(s1 ->
            Arrays.binarySearch(p, s1) >= 0).reduce((s1, s2) -> s1 + ", " + s2).get();
        model.addAttribute("msg", "用户写入(" + s + ")");
        return "message";
    }
    @GetMapping("user/allwrite")
    @RequiresPermissions(value = {"user:insert","user:delete","user:update"}, logical = Logical.AND)
    public String getUserAllWrite(Model model) {
        model.addAttribute("msg", "用户全部写入");
        return "message";
    }

}
